#!/usr/local/bin/python
# -*- coding: utf-8 -*-


import logging, traceback
from tornado.escape import json_encode,json_decode

import log
import util
import const
import time
import datetime
import user
from hall_of_fame import *

logger = logging.getLogger(__name__)


def method_enter_hall_of_fame(request,data): 
    '''进入名人堂'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_enter_hall_of_fame exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "enter_hall_of_fame"
    #设置当前位置为名人堂
    if not user.UserManager.set_user_palce(request, "hall_of_fame"):
        tmpSendMsgUtil.update_res("user_is_null")       
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    ownerUID = tmpOwnerUser.getUID()
    ownerSex = tmpOwnerUser.getSex()
    
    tmpHallOfFameManager = HallOfFameManager.instance()       #名人堂管理器     
    tmpSendMsgUtil.add_item("order_exp", tmpHallOfFameManager.getOrderByUID(ownerUID, "exp", ownerSex)) #我经验排名
    tmpSendMsgUtil.add_item("order_charm",tmpHallOfFameManager.getOrderByUID(ownerUID, "charm", ownerSex))            #我魅力排名 
    
    tmpSendMsgUtil.add_item("order_time_pre", tmpHallOfFameManager.getTimePreExec())    #上一次排序时间(秒)
    tmpSendMsgUtil.add_item("order_time_next",tmpHallOfFameManager.getTimeNextExec())   #下一次排序时间(秒)   
    tmpSendMsgUtil.send(cmd)
     
def method_get_hall_of_fame_list(request,data): 
    '''获取名人堂列表'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_get_hall_of_fame_list exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "get_hall_of_fame_list"
        
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return

    ownerUID = tmpOwnerUser.getUID()
    ownerSex = tmpOwnerUser.getSex()
    
    data_dict = json_decode(data)
    tmpReqSex = data_dict.get('sex', 0)                 #性别
    tmpReqBegin = max(data_dict.get('begin', 1), 1)     #内容begin
    tmpReqEnd = max(data_dict.get('end', 1), 1)         #内容end
    
    tmpBarOrderMax = const.Config_GetBarOrderMaxCount() #限定请求长度
    tmpDistince = tmpReqEnd-tmpReqBegin+1
    if tmpDistince > tmpBarOrderMax:
        tmpReqEnd = tmpReqBegin + tmpBarOrderMax - 1    #内容end
    
    tmpReqType = data_dict.get('type', "exp")           
    if tmpReqType not in ["exp", "charm"]: #"exp":按经验排序,  "charm":魅力排序
        tmpReqType = "exp"
         
    tmpHallOfFameManager = HallOfFameManager.instance()       #名人堂管理器
    tmpSendMsgUtil.add_item("type", tmpReqType) 
    tmpSendMsgUtil.add_item("single_total", tmpHallOfFameManager.getTotal(tmpReqType, ownerSex))   #该性别总人数
    
    tmpList = tmpHallOfFameManager.getOrderList(tmpReqBegin, tmpReqEnd, tmpReqType, tmpReqSex)
    for tmpClientDict in tmpList: #获取好友关系
        tmpUID = tmpClientDict.get("uid")
        if tmpUID:
            tmpClientDict["friend_type"]= tmpOwnerUser.getFriendType(tmpUID)  #好友类型, “default”:陌生人  “my_attt” 我关注的,  “attt_me”:关注我的, 
                                                                              # “my_hidden_love”: 我暗恋的,  ”hidden_love_me”: 暗恋我的
    tmpSendMsgUtil.add_item("single", tmpList) 
    tmpSendMsgUtil.send(cmd)


def method_hidden_love_someone(request,data): 
    '''暗恋某人'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_hidden_love_someone exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "hidden_love_someone"
        
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
     
    tmpHallOfFameManager = HallOfFameManager.instance()       #名人堂管理器  

    data_dict = json_decode(data) 
    tmpReqUID = data_dict.get('uid')                    #被暗恋者UID
    
    ownerUID = tmpOwnerUser.getUID()
    ownerSex = tmpOwnerUser.getSex()
    
    if ownerUID == tmpReqUID: #不能仰慕自己 
    	tmpSendMsgUtil.update_res("is_hidden_love_myself");
    	tmpSendMsgUtil.send(cmd)
    	return

    bTargetUserOnline = 1  #目标用户是否在线, 0:不在线, 1:在线
    tmpTargetUser = UserManager.get_user_by_uid(tmpReqUID) #用户对象  
    if tmpTargetUser is None: 
        bTargetUserOnline = 0
        tmpTargetUser = tmpHallOfFameManager.queryUserFromDB(tmpReqUID)
    if tmpTargetUser is None:
        log.print_warning(logger, "method_hidden_love_someone exec, tmpReqUID:[%s] is null" % tmpReqUID) 
        tmpSendMsgUtil.update_res("user_is_null")     
        tmpSendMsgUtil.send(cmd) 
        return
    
    if ownerSex == tmpTargetUser.getSex(): #不能仰慕同性
    	tmpSendMsgUtil.update_res("is_hidden_love_same_sex");
    	tmpSendMsgUtil.send(cmd)
    	return

    if tmpOwnerUser.isInMyAtttListUID(tmpReqUID) or tmpOwnerUser.isInMyHiddenLoveListUID(tmpReqUID): #已仰慕了对方
        tmpSendMsgUtil.update_res("had_hidden_love_user");
        tmpSendMsgUtil.send(cmd)
        return
    
    tmpJudgeConfigLogicName = "Config_hidden_love"
    #主动者判断数值是否足够
    if not util.CountUserUtil.judgeUserGameValueEnoughExt(cmd, request, ownerUID, tmpJudgeConfigLogicName):
        return
    
    #把B加入A的暗恋列表
    tmpOwnerUser.insertMyHiddenLoveMap(tmpTargetUser)  
    #把A加入B的暗恋我的列表
    tmpTargetUser.insertHiddenLoveMeMap(tmpOwnerUser)
    
    #---我的关注， 关注我的，我的好友-写DB--
    UserManager.updateDBUserMyAtttAndMyFriendAndAtttMe(tmpOwnerUser)
    UserManager.updateDBUserMyAtttAndMyFriendAndAtttMe(tmpTargetUser)
    
    tmpSendMsgUtil.send(cmd)
    
    #---'''给内存排名内的某被暗恋者   粉丝数+1'''
    tmpHallOfFameManager.addUserInfoHiddenLoveMeSize(tmpTargetUser.getUID(), tmpTargetUser.getSex())
    
    #发一条系统消息通知对方B
    tmpSendType = "add_hidden_love"
    tmpContent = "%s仰慕了你" % tmpOwnerUser.getNickname()
    tmpContentAddtion = UserManager.createDBFriendItem(tmpOwnerUser, "hidden_love_me")  #构建格式  {uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
    UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, tmpReqUID)  
    
    #发一条系统消息通知B
    tmpSendType = "add_hidden_love"
    tmpContent = "你仰慕了%s" % tmpTargetUser.getNickname()
    tmpContentAddtion = UserManager.createDBFriendItem(tmpTargetUser, "my_hidden_love", bTargetUserOnline)  #构建格式{uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
    UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, ownerUID)  
    
    #主动者数值变化----
    util.CountUserUtil.judgeAndEditExt(cmd, request, ownerUID, tmpJudgeConfigLogicName, bJudge=False)


util.registMethod("enter_hall_of_fame", method_enter_hall_of_fame)          #进入名人堂
util.registMethod("get_hall_of_fame_list", method_get_hall_of_fame_list)    #获取名人堂列表

util.registMethod("hidden_love_someone", method_hidden_love_someone)        #暗恋某人
